package com.jjty.dataGenerator.sxhcampus.service;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.builder.ExcelReaderBuilder;
import com.alibaba.excel.read.builder.ExcelReaderSheetBuilder;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jjty.dataGenerator.exception.ServiceException;
import com.jjty.dataGenerator.sxhcampus.ApiCallSxHcampus;
import com.jjty.dataGenerator.sxhcampus.SxHCampusConfig;
import com.jjty.dataGenerator.sxhcampus.mapper.EsActiveDataMapper;
import com.jjty.dataGenerator.sxhcampus.utils.ActiveDataImportReadListener;
import com.jjty.dataGenerator.sxhcampus.utils.AgentIdMap;
import com.jjty.dataGenerator.sxhcampus.utils.Coder;
import com.jjty.dataGenerator.sxhcampus.utils.RandomUtils;
import com.jjty.dataGenerator.sxhcampus.vo.*;
import com.jjty.dataGenerator.utils.HttpsRequest;
import com.jjty.dataGenerator.utils.HttpsRequest1;
import com.jjty.dataGenerator.utils.TimeUtils;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.math.BigInteger;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * @Author: huangyulong
 * @createTime: 2023-11-08 15:55
 * @Description:
 */
@Service
@Slf4j
public class SxHCampusService {

    @Autowired
    ApiCallSxHcampus apiCallSxHcampus;

    @Autowired
    ISxActiveImportLogService sxActiveImportLogService;

    @Autowired
    ISxActiveImportDataService sxActiveImportDataService;

//    @Autowired
//    AsyncBaseService asyncBaseService;

    @Autowired
    ISxActiveTemplateService sxActiveTemplateService;

    @Autowired
    private IEsActiveDataService esActiveDataService;
    @Autowired
    private EsActiveDataMapper esActiveDataMapper;

    private static final String WECHAT_WEBHOOK_URL = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=83eccc61-59ce-448a-a605-233eae5092c3"; // 企业微信群机器人Webhook地址


    // agentId与公司名称的映射关系
    private static final Map<String, String> AGENT_ID_TO_COMPANY = new HashMap<>();
    static {
        AGENT_ID_TO_COMPANY.put("508402", "快上云");
        AGENT_ID_TO_COMPANY.put("508393", "烽火");
        // 可添加更多agentId映射
    }

    /**
     * 搞一个随机数据
     * @return
     */
    public EsActiveData getRandomData(){
        int i = RandomUtils.randomInt(0, 100);
        int j = RandomUtils.randomInt(0,100);
        EsActiveData data = new EsActiveData();
        data.setTjdate("20231108");
        data.setClientId(SxHCampusConfig.appid);
        data.setPlateCode(SxHCampusConfig.plate_code);
        data.setAgentid(SxHCampusConfig.agentid);
        data.setAgreeFlag("1");
        data.setPhone(SxHCampusConfig.phone);
        data.setDeviceId("869057060012754");
        data.setDeviceFactory("阿科奇");
        data.setDeviceModel("lt30n");
        //当天累计活跃次数
        data.setAllActiveNum(RandomUtils.randomInt(5,50));
        //主动获取位置次数
        data.setInitiativePositionNum(RandomUtils.randomInt(1,10));
        //60%概率不断电，30秒上报一次，一天上报2880
        if (i > 60){
            data.setAutoPositionNum(RandomUtils.randomInt(500,2880));
        }else{
            data.setAutoPositionNum(2880);
        }
        //亲情号码通话次数
        //通话总时长
        if(i < 1){
            data.setCallphoneNum(0);
            data.setAllDuration(0);
        }else if(i < 4){
            data.setCallphoneNum(RandomUtils.randomInt(5,10));
            data.setAllDuration(RandomUtils.randomInt(2000,4000));
        }else{
            data.setCallphoneNum(RandomUtils.randomInt(1,5));
            data.setAllDuration(RandomUtils.randomInt(0,2000));
        }
        //sos次数
        if(i == 99 && j == 99){
            data.setSosphoneNum(1);
        }else{
            data.setSosphoneNum(0);
        }
        //围栏告警次数
        data.setBorderAlarmNum(RandomUtils.randomInt(0,10));
        //课堂互动答题次数
        data.setHddtNum(RandomUtils.randomInt(0,30));
        //按键号码个数
        if(i > 75){
            data.setKeyphoneNum(1);
        }else if(i > 30){
            data.setKeyphoneNum(2);
        }else{
            data.setKeyphoneNum(3);
        }
        //按键号码是否同时被三个设备绑定
        if(i > 40 && i < 50){
            data.setIsRepeatphone(1);
        }else{
            data.setIsRepeatphone(0);
        }
        data.setServerPhone(SxHCampusConfig.phone);
        data.setFamilyPhone("19980185612");
        data.setState(UUID.randomUUID().toString());
        return data;
    }

    public void importActiveData(MultipartFile file,String agentId) {
        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();
            ExcelReaderBuilder read = EasyExcel.read(inputStream, ActiveImportData.class, new ActiveDataImportReadListener(this,file.getOriginalFilename(),agentId));
            ExcelReaderSheetBuilder sheet = read.sheet(0);
            sheet.doRead();
        } catch (IOException e) {
            e.printStackTrace();
            throw new ServiceException(e);
        } catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 通过文件导入活跃数据
     * @param list
     * @param fileName
     * @param agentId
     * @throws InterruptedException
     */
    public void afterExcelAnalyse(List<ActiveImportData> list,String fileName,String agentId) throws InterruptedException {
        int i = 0,total=list.size();
        ActiveImportLog log = new ActiveImportLog();
        log.setCreateTime(new Date());
        log.setFileName(fileName);
        log.setTotalCount(total);
        sxActiveImportLogService.save(log);
        final int logId = log.getId();
        final boolean hasAgent = StringUtils.isNotBlank(agentId);
        for (ActiveImportData data : list) {
            if(hasAgent){
                data.setAgentId(agentId);
            }else{
                data.setAgentId(AgentIdMap.getAgentIdByCityName(data.getCity()));
            }
            data.setLogId(logId);
            EsActiveData randomData = getRandomData();
            randomData.setAgentid(data.getAgentId());
            randomData.setPhone(data.getPhone());
            randomData.setDeviceId(data.getImei());
            randomData.setServerPhone(data.getPhone());
            randomData.setDeviceFactory("阿科奇");
            randomData.setDeviceFactory("lt30n");
            randomData.setFamilyPhone(data.getPhone().substring(0,3)+RandomUtils.randomInt(10000000,99999999));
            randomData.setTjdate(data.getTjdate());
            System.out.println(JSONObject.toJSONString(randomData));
            //continue;
            try{
                String concatStr = Coder.getConcatStr(randomData);
                String s = Coder.hmac_sha1(concatStr, SxHCampusConfig.appkey);
                s = new BigInteger(s.getBytes("UTF-8")).toString();
                System.out.println(concatStr);
                System.out.println(s);
                randomData.setSig(s);

//                BaseResultSx baseResultSx = new BaseResultSx();
//                if (randomData.getFamilyPhone().endsWith("6") || randomData.getFamilyPhone().endsWith("7")){
//                    int a = 1/0;
//                }
//                if (randomData.getFamilyPhone().endsWith("5") || randomData.getFamilyPhone().endsWith("0")){
//                    throw new ServiceException("没有订购关系");
//                }

                BaseResultSx baseResultSx = apiCallSxHcampus.sendActiveData(randomData);
                data.setMsg(baseResultSx.getMsg());
                System.out.println(JSONObject.toJSONString(baseResultSx));
                i++;
            }catch (Exception e){
                if(e.getMessage().length() > 250){
                    data.setMsg(e.getMessage().substring(0,250));
                }else{
                    data.setMsg(e.getMessage());
                }
                e.printStackTrace();
                data.setStatus(2);
            }
            Thread.sleep(100L);
        }
        System.out.println("总共:"+total+"  成功:"+i  +"失败:"+(total-i));
        try{
            log.setSuccessCount(i);
            log.setFailureCount(total-i);
            log.setStatus(1);
            sxActiveImportLogService.updateById(log);
            sxActiveImportDataService.saveBatch(list);
            System.out.println("------>本机记录完成");
        }catch (Exception e){
            e.printStackTrace();
        }
        System.out.println("总共:"+total+"  成功:"+i  +"失败:"+(total-i));
    }

    public void importActiveData(OAQueryOrderResult result,String startTime,String endTime) {

        //今天日期格式化
        Date date = new Date();
        String today = TimeUtils.getFormat("yyyyMMdd",date);
        //记录导入日志
        ActiveImportLog log = new ActiveImportLog();
        //昨天日期格式化
        log.setCreateTime(date);
        log.setFileName("定时导入("+startTime+"~"+endTime+")");
        if (result.success()){
            log.setTotalCount(result.getData().size());
        }else{
            log.setTotalCount(0);
            log.setRemark(result.getMsg());
        }
        sxActiveImportLogService.save(log);

        //处理导入数据
        if(result.success() && !result.getData().isEmpty()){
            List<ActiveImportData> aidList = new ArrayList<>();
            final int logId = log.getId();
            int i = 0;//成功数
            for (OAOrderData datum : result.getData()) {
                ActiveImportData data = datum.getImportData(logId);
                data.setTjdate(today);
                aidList.add(data);

                EsActiveData randomData = getRandomData();
                randomData.setAgentid(data.getAgentId());
                randomData.setPhone(data.getPhone());
                randomData.setDeviceId(data.getImei());
                randomData.setServerPhone(data.getPhone());
                randomData.setDeviceFactory("阿科奇");
                randomData.setDeviceFactory("lt30n");
                randomData.setFamilyPhone(data.getPhone().substring(0,3)+RandomUtils.randomInt(10000000,99999999));
                randomData.setTjdate(data.getTjdate());
                System.out.println(JSONObject.toJSONString(randomData));
                //continue;
                try{
                    Thread.sleep(100L);
                    String concatStr = Coder.getConcatStr(randomData);
                    String s = Coder.hmac_sha1(concatStr, SxHCampusConfig.appkey);
                    s = new BigInteger(s.getBytes("UTF-8")).toString();
                    System.out.println(concatStr);
                    System.out.println(s);
                    randomData.setSig(s);

//                    BaseResultSx baseResultSx = new BaseResultSx();
//                    if (randomData.getFamilyPhone().endsWith("6") || randomData.getFamilyPhone().endsWith("7")){
//                        int a = 1/0;
//                    }
//                    if (randomData.getFamilyPhone().endsWith("5") || randomData.getFamilyPhone().endsWith("0")){
//                        throw new ServiceException("没有订购关系");
//                    }

                    BaseResultSx baseResultSx = apiCallSxHcampus.sendActiveData(randomData);
                    data.setMsg(baseResultSx.getMsg());
                    System.out.println(JSONObject.toJSONString(baseResultSx));
                    i++;
                }catch (Exception e){
                    //记录失败原因
                    if(e.getMessage().length() > 250){
                        data.setMsg(e.getMessage().substring(0,250));
                    }else{
                        data.setMsg(e.getMessage());
                    }
                    e.printStackTrace();
                    data.setStatus(2);
                }
            }
            System.out.println("总共:"+log.getTotalCount()+"  成功:"+i  +"失败:"+(log.getTotalCount()-i));
            try{
                log.setSuccessCount(i);
                log.setFailureCount(log.getTotalCount()-i);
                log.setStatus(1);
                sxActiveImportLogService.updateById(log);
                sxActiveImportDataService.saveBatch(aidList);
                System.out.println("------>本机记录完成");
            }catch (Exception e){
                e.printStackTrace();
            }
            System.out.println("总共:"+log.getTotalCount()+"  成功:"+i  +"失败:"+(log.getTotalCount()-i));
        }
    }


    /**
     * 导入每日全量活跃数据
     * @param result
     * @param startTime
     * @param endTime
     */
    public void importActiveDataAll(OAQueryOrderResult result, String startTime, String endTime, String batchNumber) {
        Integer startTimeInt = Integer.valueOf(startTime);

        // 今天日期格式化
        Date date = new Date();
        String today = TimeUtils.getFormat("yyyyMMdd", date);

        // 记录导入日志
        ActiveImportLog log = new ActiveImportLog();
        log.setBatchNumber(batchNumber);
        log.setCreateTime(date);
        log.setFileName("定时导入(" + startTime + "~" + endTime + ")");
        if (result.success()) {
            log.setTotalCount(result.getData().size());
        } else {
            log.setTotalCount(0);
            log.setRemark(result.getMsg());
        }
        sxActiveImportLogService.save(log);

        // 处理导入数据
        if (result.success() && !result.getData().isEmpty()) {
            List<ActiveImportData> aidList = new ArrayList<>();
            final int logId = log.getId();
            int i = 0; // 成功数
            for (OAOrderData datum : result.getData()) {
                ActiveImportData data = datum.getImportData(logId);
                if (startTimeInt >= 20240701) {
                    // 20240701 之后的全部统一成快上云的代理商 id
                    data.setAgentId("508402");
                }
                data.setTjdate(today);
                aidList.add(data);
            }

            // 保存数据到本地数据库
            try {
                sxActiveImportDataService.saveBatch(aidList);
                log.setSuccessCount(aidList.size());
                log.setFailureCount(0);
                log.setStatus(1);
                sxActiveImportLogService.updateById(log);
                i = aidList.size();
            } catch (Exception e) {
                e.printStackTrace();
                log.setStatus(2);
                log.setRemark("数据保存到本地数据库失败：" + e.getMessage());
                sxActiveImportLogService.updateById(log);
                return;
            }

            System.out.println("总共:" + log.getTotalCount() + "  成功:" + i + " 失败:" + (log.getTotalCount() - i));

            //transformAndSaveToEsActiveData(aidList);
            //pushImportedData(log, aidList);
        }
    }
    public void transformAndSaveAllData() {
        // 查询 sx_active_import_data 表中的所有数据
        QueryWrapper<ActiveImportData> queryWrapper = new QueryWrapper<>();
        List<ActiveImportData> aidList = sxActiveImportDataService.list(queryWrapper);

        List<EsActiveData> esActiveDataList = new ArrayList<>();
        Random random = new Random();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");

        for (ActiveImportData data : aidList) {
            EsActiveData randomData = getRandomData();
            randomData.setAgentid(data.getAgentId());
            randomData.setPhone(data.getPhone());
            randomData.setDeviceId(data.getImei());
            randomData.setServerPhone(data.getPhone());
            randomData.setDeviceFactory("阿科奇");
            randomData.setDeviceModel("lt30n");
            randomData.setFamilyPhone(data.getPhone().substring(0,3)+RandomUtils.randomInt(10000000,99999999));
            randomData.setTjdate(LocalDateTime.now().format(formatter));
            //System.out.println(JSONObject.toJSONString(randomData));

            try {
                String concatStr = Coder.getConcatStr(randomData);
                String signature = Coder.hmac_sha1(concatStr, SxHCampusConfig.appkey);
                signature = new BigInteger(signature.getBytes("UTF-8")).toString();
                randomData.setSig(signature);

            } catch (Exception e) {
                System.err.println("签名生成失败: " + e.getMessage());
                e.printStackTrace();
                // 若签名生成失败，可设置默认值或跳过该数据
                randomData.setSig("SIGN_ERROR");
            }

            System.out.println(JSONObject.toJSONString(randomData));
            esActiveDataList.add(randomData);
        }

        // 保存到 es_active_data 表中
        try {
            esActiveDataService.saveBatch(esActiveDataList);
            System.out.println("数据已成功保存到 es_active_data 表中，共 " + esActiveDataList.size() + " 条");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("数据保存到 es_active_data 表中失败：" + e.getMessage());
        }
    }



    @Getter
    private Map<String, Object> statisticsData = new HashMap<>();

    public void clearStatisticsData() {
        statisticsData.clear();
    }

    public void sendAllActiveData() {
        log.info("开始处理活跃数据推送任务");
        int pageSize = 1000;
        int pageNum = 1;

        int totalSuccess = 0;
        int totalFailure = 0;
        Map<String, AgentResult> agentResultMap = new HashMap<>();

        while (true) {
            Page<EsActiveData> page = new Page<>(pageNum, pageSize);
            Page<EsActiveData> dataPage = esActiveDataMapper.selectPage(page, null);
            List<EsActiveData> activeDataList = dataPage.getRecords();

            if (CollectionUtils.isEmpty(activeDataList)) {
                log.info("所有数据处理完成，没有更多待发送数据");
                break;
            }

            Long totalSize = dataPage.getTotal();
            int currentPageSize = activeDataList.size();
            int expectedPageSize = pageSize;

            if (currentPageSize < expectedPageSize) {
                log.info("检测到可能是最后一页，当前页数据量: {}, 预期: {}", currentPageSize, expectedPageSize);
            }

            log.info("当前处理第{}页，共{}条数据", pageNum, activeDataList.size());

            PageProcessResult result = processDataPage(activeDataList, agentResultMap);
            totalSuccess += result.getSuccessCount();
            totalFailure += result.getFailureCount();

            if (pageNum * pageSize >= totalSize) {
                log.info("已处理到最后一页，总页码: {}, 总数据量: {}", pageNum, totalSize);
                break;
            }

            pageNum++;
        }

        log.info("所有活跃数据推送任务完成，总数: {}, 成功: {}, 失败: {}",
                totalSuccess + totalFailure, totalSuccess, totalFailure);
        // 保存统计数据
        statisticsData.put("totalSuccess", totalSuccess);
        statisticsData.put("totalFailure", totalFailure);
        statisticsData.put("agentResultMap", agentResultMap);
        log.info("统计数据已保存: {}", JSONObject.toJSONString(statisticsData));

        //sendWechatNotification(totalSuccess, totalFailure, agentResultMap);
    }

    /**
     * 处理当前页数据并按agentId统计结果
     */
    private PageProcessResult processDataPage(List<EsActiveData> dataList,
                                              Map<String, AgentResult> agentResultMap) {
        int totalCount = dataList.size();
        int successCount = 0;
        int failureCount = 0;

        for (EsActiveData activeData : dataList) {
            boolean isSuccess = false;
            int retryTimes = 0;
            final int MAX_RETRIES = 3;
            String agentId = activeData.getAgentid(); // 获取agentId

            while (!isSuccess && retryTimes < MAX_RETRIES) {
                try {
                    String requestData = JSONObject.toJSONString(activeData);
                    log.info("发送数据[agentId:{}][ID:{}]: {}",
                            agentId, activeData.getId(), requestData);

                    String response = HttpsRequest.sendPost(SxHCampusConfig.sendActiveDataUrl, requestData);
                    System.out.println(response);
                    log.info("API响应[agentId:{}][ID:{}]: {}",
                            agentId, activeData.getId(), response);

                    BaseResultSx result = JSONObject.parseObject(response, BaseResultSx.class);

                    if (result.getRet() == 0) {
                        activeData.setStatus(1);
                        activeData.setMsg("发送成功");
                        successCount++;
                        isSuccess = true;
                        log.info("数据发送成功[agentId:{}][ID:{}]", agentId, activeData.getId());
                        updateAgentResult(agentResultMap, agentId, true, false);
                    } else {
                        activeData.setStatus(2);
                        activeData.setMsg(truncateErrorMessage(result.getMsg()));
                        failureCount++;
                        isSuccess = true;
                        log.error("API调用失败[agentId:{}][ID:{}]: {}",
                                agentId, activeData.getId(), result.getMsg());
                        updateAgentResult(agentResultMap, agentId, false, true);
                    }
                } catch (Exception e) {
                    retryTimes++;
                    log.error("发送数据异常[agentId:{}][ID:{}][重试{}次]: {}",
                            agentId, activeData.getId(), retryTimes, e.getMessage(), e);

                    if (retryTimes < MAX_RETRIES) {
                        log.info("5分钟后重试[agentId:{}][ID:{}]...", agentId, activeData.getId());
                        try {
                            Thread.sleep(5 * 60 * 1000);
                        } catch (InterruptedException ex) {
                            log.warn("重试休眠被中断", ex);
                            Thread.currentThread().interrupt();
                        }
                    } else {
                        activeData.setStatus(2);
                        activeData.setMsg(truncateErrorMessage("系统异常: " + e.getMessage() + " (已重试" + MAX_RETRIES + "次)"));
                        failureCount++;
                        log.error("超过最大重试次数[agentId:{}][ID:{}]: {}",
                                agentId, activeData.getId(), e.getMessage());
                        updateAgentResult(agentResultMap, agentId, false, true);
                    }
                } finally {
                    if (isSuccess || retryTimes >= MAX_RETRIES) {
                        try {
                            updateActiveDataStatus(activeData);
                        } catch (Exception ex) {
                            log.error("更新数据状态失败[agentId:{}][ID:{}]: {}",
                                    agentId, activeData.getId(), ex.getMessage(), ex);
                        }
                    }
                    try {
                        Thread.sleep(100L);
                    } catch (InterruptedException ex) {
                        log.warn("线程休眠被中断", ex);
                        Thread.currentThread().interrupt();
                    }
                }
            }
        }

        log.info("当前页处理完成: 总数={}, 成功={}, 失败={}",
                totalCount, successCount, failureCount);
        return new PageProcessResult(successCount, failureCount);
    }

    /**
     * 发送企业微信通知（包含按agentId的统计和公司名称）
     */
    public void sendWechatNotification(int totalSuccess, int totalFailure,
                                        Map<String, AgentResult> agentResultMap) {
        try {
            URL url = new URL(WECHAT_WEBHOOK_URL);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setDoOutput(true);

            StringBuilder content = new StringBuilder();
            content.append("**活跃数据推送任务完成通知**\n\n");
            content.append("**总统计**\n");
            content.append("总推送数据量：").append(totalSuccess + totalFailure).append(" 条\n");
            content.append("成功数量：").append(totalSuccess).append(" 条  \n");
            content.append("失败数量：").append(totalFailure).append(" 条  \n");
            content.append("成功率：").append(String.format("%.2f%%", totalSuccess * 100.0 / (totalSuccess + totalFailure))).append("\n\n");
            content.append("**按代理商统计**\n");

            for (Map.Entry<String, AgentResult> entry : agentResultMap.entrySet()) {
                String agentId = entry.getKey();
                AgentResult result = entry.getValue();
                int agentTotal = result.getSuccessCount() + result.getFailureCount();
                double successRate = agentTotal > 0 ? result.getSuccessCount() * 100.0 / agentTotal : 0;

                // 获取公司名称，若无映射则显示agentId
                String companyName = AGENT_ID_TO_COMPANY.getOrDefault(agentId, "agentId:" + agentId);

                content.append("- **").append(companyName).append("**\n");
                content.append("  推送量：").append(agentTotal).append(" 条\n");
                content.append("  成功：").append(result.getSuccessCount()).append(" 条\n");
                content.append("  失败：").append(result.getFailureCount()).append(" 条\n");
                content.append("  成功率：").append(String.format("%.2f%%", successRate)).append("\n");
            }

            //content.append("\n**任务完成时间**：").append(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));

            String jsonBody = "{\"msgtype\": \"markdown\", \"markdown\": {\"content\": \"" +
                    content.toString().replace("\"", "\\\"") + "\"}}";

            try (OutputStream os = connection.getOutputStream()) {
                byte[] input = jsonBody.getBytes(StandardCharsets.UTF_8);
                os.write(input, 0, input.length);
            }

            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                try (BufferedReader br = new BufferedReader(
                        new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
                    StringBuilder response = new StringBuilder();
                    String responseLine;
                    while ((responseLine = br.readLine()) != null) {
                        response.append(responseLine.trim());
                    }
                    log.info("企业微信消息发送成功，响应: {}", response);
                }
            } else {
                try (BufferedReader br = new BufferedReader(
                        new InputStreamReader(connection.getErrorStream(), StandardCharsets.UTF_8))) {
                    StringBuilder response = new StringBuilder();
                    String responseLine;
                    while ((responseLine = br.readLine()) != null) {
                        response.append(responseLine.trim());
                    }
                    log.error("企业微信消息发送失败，状态码: {}, 错误信息: {}", responseCode, response);
                }
            }
        } catch (IOException e) {
            log.error("发送企业微信通知时发生异常", e);
        }
    }

    /**
     * 更新agentId的统计结果
     */
    private void updateAgentResult(Map<String, AgentResult> agentResultMap,
                                   String agentId, boolean success, boolean failure) {
        AgentResult result = agentResultMap.computeIfAbsent(agentId, k -> new AgentResult());
        if (success) result.incrementSuccess();
        if (failure) result.incrementFailure();
    }

    /**
     * 分页处理结果封装类
     */
    private static class PageProcessResult {
        private final int successCount;
        private final int failureCount;
        public PageProcessResult(int successCount, int failureCount) {
            this.successCount = successCount;
            this.failureCount = failureCount;
        }
        public int getSuccessCount() { return successCount; }
        public int getFailureCount() { return failureCount; }
    }

    /**
     * 按agentId统计的结果类
     */
    public static class AgentResult {
        private int successCount = 0;
        private int failureCount = 0;
        public void incrementSuccess() { successCount++; }
        public void incrementFailure() { failureCount++; }
        public int getSuccessCount() { return successCount; }
        public int getFailureCount() { return failureCount; }
    }


    // 辅助方法：截断错误信息，避免超出数据库字段长度
    private String truncateErrorMessage(String message) {
        if (message == null) {
            return "未知错误";
        }
        return message.length() > 250 ? message.substring(0, 250) : message;
    }

    // 辅助方法：更新数据状态到数据库
    private void updateActiveDataStatus(EsActiveData activeData) {
        // 根据您的实际数据访问层实现更新状态
        // 示例：sxActiveImportDataService.updateStatus(activeData.getId(), activeData.getStatus(), activeData.getMsg());

        // 假设您使用MyBatis-Plus，可这样实现：
        EsActiveData updateRecord = new EsActiveData();
        updateRecord.setId(activeData.getId());
        updateRecord.setStatus(activeData.getStatus());
        updateRecord.setMsg(activeData.getMsg());
        esActiveDataMapper.updateById(updateRecord);
    }


    public void syncActiveTemplateAll(String startTime, List<OAOrderData> list) {
        List<SxActiveTemplate> templates = new ArrayList<>();
        for (OAOrderData datum : list) {
            SxActiveTemplate template = new SxActiveTemplate();
            //咸阳：快上云：508402   其他：烽火万家：508393
//          data.setAgentId(city.equals("咸阳市")?"508402":"508393");
            template.setAgentId(AgentIdMap.getAgentIdByCityName(datum.getCity()));
            template.setCity(datum.getCity());
            template.setArea(datum.getDistrict());
            template.setHzName(datum.getChildName());
            template.setKhName(datum.getParentName());
            template.setSdName(datum.getUser_name());
            template.setImei(datum.getDevice());
            template.setPhone(datum.getOrder_phone());
            template.setTjdate(startTime);
            if(Integer.parseInt(startTime) >= 20240701){
                //20240701之后的全部统一成快上云的代理商id
                template.setAgentId("508402");
            }
            templates.add(template);
            System.out.println(JSONObject.toJSONString(template));
        }
        sxActiveTemplateService.saveBatch(templates);
    }

    public void syncActiveTemplateForDay(List<OAOrderData> list, String date) {
        List<SxActiveTemplate> addList = new ArrayList<>();
        for (OAOrderData data : list) {
            SxActiveTemplate template = sxActiveTemplateService.getByImei(data.getDevice());
            if(template == null){
                template = new SxActiveTemplate();
                template.setAgentId(AgentIdMap.getAgentIdByCityName(data.getCity()));
                template.setCity(data.getCity());
                template.setArea(data.getDistrict());
                template.setHzName(data.getChildName());
                template.setKhName(data.getParentName());
                template.setSdName(data.getUser_name());
                template.setImei(data.getDevice());
                template.setPhone(data.getOrder_phone());
                template.setTjdate(date);
                if(Integer.parseInt(date) >= 20240701){
                    //20240701之后的全部统一成快上云的代理商id
                    template.setAgentId("508402");
                }
                addList.add(template);
                System.out.println(JSONObject.toJSONString(template));
            }else{
                //更新手机，代理商

            }
        }
        sxActiveTemplateService.saveBatch(addList);
    }

    public void testSendAllActiveData() {
        log.info("开始模拟测试活跃数据推送");
        int pageSize = 1000; // 每次模拟处理1000条数据
        int pageNum = 1;     // 页码从1开始
        int totalSuccess = 0;
        int totalFailure = 0;
        Map<String, AgentResult> agentResultMap = new HashMap<>();

        while (true) {
            // 1. 查询所有数据（模拟数据库查询）
            List<EsActiveData> activeDataList = esActiveDataMapper.selectList(null);
            int totalSize = activeDataList.size();

            // 2. 计算当前页索引（修复逻辑）
            int startIdx = (pageNum - 1) * pageSize;

            // 关键改进：当startIdx超出范围时结束循环
            if (startIdx >= totalSize) {
                if (startIdx == 0) { // 特殊情况：没有数据
                    log.info("没有待测试的活跃数据");
                } else {
                    log.info("所有数据处理完成，最后一页索引范围: {}~{}",
                            Math.max(0, startIdx - pageSize), totalSize - 1);
                }
                break;
            }

            // 修正：endIdx应该是startIdx+pageSize或totalSize的较小值
            int endIdx = Math.min(startIdx + pageSize, totalSize);

            // 3. 截取当前页数据
            List<EsActiveData> pageData = activeDataList.subList(startIdx, endIdx);

            // 4. 处理当前页数据
            log.info("模拟处理第{}页，数据范围: {}~{}，共{}条",
                    pageNum, startIdx, endIdx - 1, pageData.size());

            PageResult result = processTestDataPage(pageData);
            //PageProcessResult result = processDataPage(activeDataList, agentResultMap);
            totalSuccess += result.getSuccessCount();
            totalFailure += result.getFailureCount();

            // 5. 页码递增
            pageNum++;
        }

        log.info("模拟测试全部完成: 总数={}, 成功={}, 失败={}",
                totalSuccess + totalFailure, totalSuccess, totalFailure);

        // 保存统计数据
        statisticsData.put("totalSuccess", totalSuccess);
        statisticsData.put("totalFailure", totalFailure);
        statisticsData.put("agentResultMap", agentResultMap);
        log.info("统计数据已保存: {}", JSONObject.toJSONString(statisticsData));

        // 发送企业微信通知
        //sendWechatNotification(totalSuccess, totalFailure);
    }

    /**
     * 发送企业微信通知
     */
//    private void sendWechatNotification(int successCount, int failureCount) {
//        try {
//            URL url = new URL(WEBHOOK_URL);
//            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
//            connection.setRequestMethod("POST");
//            connection.setRequestProperty("Content-Type", "application/json");
//            connection.setDoOutput(true);
//
//            // 构建消息内容
//            String content = "活跃数据推送测试结果通知\n" +
//                    "总推送数：" + (successCount + failureCount) + " 条\n" +
//                    "成功数：" + successCount + " 条\n" +
//                    "失败数：" + failureCount + " 条\n" +
//                    "成功率：" + String.format("%.2f%%", successCount * 100.0 / (successCount + failureCount));
//
//            String jsonBody = "{\"msgtype\": \"text\", \"text\": {\"content\": \"" + content + "\"}}";
//
//            try (OutputStream os = connection.getOutputStream()) {
//                byte[] input = jsonBody.getBytes(StandardCharsets.UTF_8);
//                os.write(input, 0, input.length);
//            }
//
//            int responseCode = connection.getResponseCode();
//            if (responseCode == HttpURLConnection.HTTP_OK) {
//                try (BufferedReader br = new BufferedReader(
//                        new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
//                    StringBuilder response = new StringBuilder();
//                    String responseLine;
//                    while ((responseLine = br.readLine()) != null) {
//                        response.append(responseLine.trim());
//                    }
//                    log.info("企业微信消息发送成功，响应: {}", response);
//                }
//            } else {
//                log.error("企业微信消息发送失败，状态码: {}", responseCode);
//            }
//        } catch (IOException e) {
//            log.error("发送企业微信通知时发生异常", e);
//        }
//    }

    /**
     * 处理当前页测试数据（包含重试逻辑）
     */
    private PageResult processTestDataPage(List<EsActiveData> dataList) {
        int successCount = 0;
        int failureCount = 0;
        int retryCount = 0;
        final int MAX_RETRIES = 3; // 最大重试次数
        final double EXCEPTION_RATE = 0.0001; // 异常抛出比例，1%

        for (EsActiveData activeData : dataList) {
            boolean isSuccess = false;
            int retryTimes = 0;

            while (!isSuccess && retryTimes < MAX_RETRIES) {
                try {
                    // 1. 控制1%的概率抛出异常
                    if (Math.random() < EXCEPTION_RATE) {
                        throw new RuntimeException("模拟系统异常");
                    }

                    // 2. 模拟50%成功率（可调整比例）
                    boolean mockSuccess = Math.random() > 0.5;

                    if (mockSuccess) {
                        // 模拟成功
                        activeData.setStatus(1);
                        activeData.setMsg("模拟发送成功");
                        successCount++;
                        isSuccess = true;
                        log.info("模拟成功[ID:{}]", activeData.getId());
                    } else {
                        // 模拟API调用失败
                        activeData.setStatus(2);
                        activeData.setMsg("模拟API调用失败");
                        failureCount++;
                        isSuccess = true;
                        log.error("模拟失败[ID:{}]", activeData.getId());
                    }
                } catch (Exception e) {
                    // 模拟系统异常，需要重试
                    retryTimes++;
                    retryCount++;
                    log.info("模拟异常[ID:{}][重试{}次]: {}", activeData.getId(), retryTimes, e.getMessage());

                    if (retryTimes < MAX_RETRIES) {
                        // 模拟休眠5分钟（测试时缩短为5秒）
                        log.info("模拟5秒后重试[ID:{}]...", activeData.getId());
                        try {
                            Thread.sleep(5000); // 5秒
                        } catch (InterruptedException ex) {
                            log.warn("模拟重试休眠被中断", ex);
                            Thread.currentThread().interrupt();
                        }
                    } else {
                        // 超过最大重试次数
                        activeData.setStatus(2);
                        activeData.setMsg("模拟异常: 超过最大重试次数");
                        failureCount++;
                        log.error("模拟超过最大重试次数[ID:{}]", activeData.getId());
                    }
                } finally {
                    if (isSuccess || retryTimes >= MAX_RETRIES) {
                        // 处理完成或超过重试次数时更新状态
                        try {
                            updateActiveDataStatus(activeData);
                        } catch (Exception ex) {
                            log.error("更新数据状态失败[ID:{}]: {}", activeData.getId(), ex.getMessage());
                        }
                    }
                }
            }
        }

        log.info("当前页模拟结果: 成功={}, 失败={}, 重试={}",
                successCount, failureCount, retryCount);
        return new PageResult(successCount, failureCount);
    }
    /**
     * 分页处理结果封装类
     */
    private static class PageResult {
        private final int successCount;
        private final int failureCount;

        public PageResult(int successCount, int failureCount) {
            this.successCount = successCount;
            this.failureCount = failureCount;
        }

        public int getSuccessCount() { return successCount; }
        public int getFailureCount() { return failureCount; }
    }
}